package com.ruoyi.college.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.college.mapper.TeacherMapper;
import com.ruoyi.college.domain.Teacher;
import com.ruoyi.college.service.ITeacherService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import javax.validation.Validator;

/**
 * 教师信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-24
 */
@Service
public class TeacherServiceImpl implements ITeacherService 
{
    private static final Log log = LogFactory.getLog(TeacherServiceImpl.class);

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService userService;


    /**
     * 查询教师信息
     * 
     * @param teacherId 教师信息主键
     * @return 教师信息
     */
    @Override
    public Teacher selectTeacherByTeacherId(Long teacherId)
    {
        return teacherMapper.selectTeacherByTeacherId(teacherId);
    }

    /**
     * 查询教师信息列表
     * 
     * @param teacher 教师信息
     * @return 教师信息
     */
    @Override
    public List<Teacher> selectTeacherList(Teacher teacher)
    {
        return teacherMapper.selectTeacherList(teacher);
    }

    /**
     * 新增教师信息
     * 
     * @param teacher 教师信息
     * @return 结果
     */
    @Override
    public int insertTeacher(Teacher teacher)
    {
        teacher.setCreateTime(DateUtils.getNowDate());
        //系统创建用户，授权


        //同步用户信息
        SysRole role = roleMapper.selectRoleByRoleKey("courseTeacher");
        SysUser user = new SysUser();
        user.setCreateBy(ShiroUtils.getLoginName());
        user.setPhonenumber(teacher.getPhone());
        user.setLoginName(teacher.getTeacherNo());
        user.setUserName(teacher.getTeacherName());
        String password = configService.selectConfigByKey("sys.user.initPassword");
        user.setSalt(ShiroUtils.randomSalt());
        user.setEmail(teacher.getEmail());
        user.setPassword(new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex());
        user.setSex("2");
        user.setRoleIds(new Long[]{role.getRoleId()});
        userService.insertUser(user);
        return teacherMapper.insertTeacher(teacher);
    }

    /**
     * 修改教师信息
     * 
     * @param teacher 教师信息
     * @return 结果
     */
    @Override
    public int updateTeacher(Teacher teacher)
    {
        return teacherMapper.updateTeacher(teacher);
    }

    /**
     * 批量删除教师信息
     * 
     * @param teacherIds 需要删除的教师信息主键
     * @return 结果
     */
    @Override
    public int deleteTeacherByTeacherIds(String teacherIds)
    {
        return teacherMapper.deleteTeacherByTeacherIds(Convert.toStrArray(teacherIds));
    }

    /**
     * 删除教师信息信息
     * 
     * @param teacherId 教师信息主键
     * @return 结果
     */
    @Override
    public int deleteTeacherByTeacherId(Long teacherId)
    {
        return teacherMapper.deleteTeacherByTeacherId(teacherId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertBatchTeacher(List<Teacher> teacherList, boolean updateSupport, String operName) {
        if (teacherList == null || teacherList.isEmpty()) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        int successNum = 0;
        int failureNum = 0;
        //校验传入的教师信息是否重复
        this.validateTeacherListRepeat(teacherList);

        List<Teacher> teachers = teacherMapper.selectTeacherList(new Teacher());
        Map<String, Teacher> teacherMap = teachers.stream()
                .collect(Collectors.toMap(Teacher::getTeacherNo, teacher -> teacher));
        List<SysUser> userList = userService.selectUserList(new SysUser());
        Map<String, SysUser> userMap = userList.stream()
                .collect(Collectors.toMap(SysUser::getLoginName, sysUser -> sysUser));
        SysRole role = roleMapper.selectRoleByRoleKey("courseTeacher");
        List<Teacher> teacherUpdate = new ArrayList<>();
        List<Teacher> teacherInsert = new ArrayList<>();
        List<SysUser> userUpdate = new ArrayList<>();
        List<SysUser> userInsert = new ArrayList<>();
        for (Teacher teacher : teacherList) {
            // 验证是否存在这个用户
            Teacher teacherOld = teacherMap.get(teacher.getTeacherNo());
            if (teacherOld == null) {
                teacherInsert.add(teacher);
                SysUser user = new SysUser();
                user.setCreateBy(operName);
                user.setPhonenumber(teacher.getPhone());
                user.setLoginName(teacher.getTeacherNo());
                user.setUserName(teacher.getTeacherName());
                String password = configService.selectConfigByKey("sys.user.initPassword");
                user.setSalt(ShiroUtils.randomSalt());
                user.setEmail(teacher.getEmail());
                user.setPassword(new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex());
                user.setSex("2");
                user.setRoleIds(new Long[]{role.getRoleId()});
                userInsert.add(user);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、教师姓名 ").append(teacher.getTeacherName()).append(" 导入成功");
            } else if (updateSupport) {
                teacher.setTeacherId(teacherOld.getTeacherId());
                teacherUpdate.add(teacher);
                SysUser user = userMap.get(teacher.getTeacherNo());
                user.setUpdateTime(new Date());
                user.setUpdateBy(operName);
                user.setUserName(teacher.getTeacherName());
                user.setEmail(teacher.getEmail());
                userUpdate.add(user);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、教师姓名 ").append(teacher.getTeacherName()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、教师姓名 ").append(teacher.getTeacherName()).append(" 已存在");
            }
        }
        this.handleTeacherUserBatch(teacherUpdate, teacherInsert, userUpdate, userInsert);
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    private void validateTeacherListRepeat(List<Teacher> teacherList) {
        Set<String> teacherNoSet = new HashSet<>();
        for (Teacher teacher : teacherList) {
            if (!teacherNoSet.contains(teacher.getTeacherNo())) {
                teacherNoSet.add(teacher.getTeacherNo());
            } else {
                throw new ServiceException("导入教师数据不能有重复工号！");
            }
        }
    }

    private void handleTeacherUserBatch(List<Teacher> teacherUpdate, List<Teacher> teacherInsert, List<SysUser> userUpdate,
                                        List<SysUser> userInsert) {
        if (!teacherInsert.isEmpty()) {
            teacherInsert.forEach(teacher -> {
                teacherMapper.insertTeacher(teacher);
            });
        }
        if (!teacherUpdate.isEmpty()) {
            teacherUpdate.forEach(teacher -> {
                teacherMapper.updateTeacher(teacher);
            });
        }
        if (!userInsert.isEmpty()) {
            userInsert.forEach(user -> {
                userService.insertUser(user);
            });
        }
        if (!userUpdate.isEmpty()) {
            userUpdate.forEach(user -> {
                userService.updateUser(user);
            });
        }
    }
}
